package com.uniview.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

public class WorkpulsUtil {

	private static Logger logger = Logger.getLogger(WorkpulsUtil.class);

	/**
	 * 向指定 URL 发送POST方法的请求
	 * 
	 * @param url
	 *            发送请求的 URL
	 * @param param
	 *            请求参数，请求参数应该是。(JSON数据)
	 * @return 所代表远程资源的响应结果
	 */
	public static String sendHttpRequest(String url, String param, String requestMethod) {
		OutputStream outputStream = null;
		PrintWriter out = null;
		BufferedReader in = null;
		String result = "";
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
			// 设置通用的请求属性
			conn.setRequestProperty("Content-Type", "text/html");
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

			conn.setRequestMethod(requestMethod);
			conn.setUseCaches(false);
			conn.setInstanceFollowRedirects(true);
			conn.setDoOutput(true);
			conn.setDoInput(true);

			// 获取URLConnection对象对应的输出流
			// 为请求添加json参数
			if (StringUtils.isNotBlank(param)) {
				outputStream = conn.getOutputStream();
				outputStream.write(param.getBytes());
				outputStream.flush();
			}

			// 发送请求参数
			// out = new PrintWriter(conn.getOutputStream());
			// out.print(param);
			// flush输出流的缓冲
			// out.flush();

			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
			conn.disconnect();
		} catch (Exception e) {
			logger.error("发送HTTP请求异常", e);
			e.printStackTrace();
		} finally {
			// 使用finally块来关闭输出流、输入流
			try {
				if (out != null) {
					out.close();
				}
				if (outputStream != null) {
					outputStream.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
				logger.error("发送HTTP请求异常", ex);
			}
		}
		return result;
	}

}
